<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: green;
        }
        button{
            margin-top: 200px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    <button class="btn1" onclick="goNext(400)">400</button>
    <button class="btn2" onclick="goNext(800)">800</button>

    <script>
        var box = document.querySelector('.box');
        var btn1 = document.querySelector('.btn');
        var btn2 = document.querySelector('.btn2');

        // 闪现动画
        // function goNext(target) {
        //     box.style.left = target + 'px'
        // }

        // 匀速动画
        function goNext(target) {
            move(box, target)
        }
        function move(el, target) {
            // 挂载定时器timer在box上
            clearInterval(el.timer);
            var current = el.offsetLeft;
            // 如果相等了，就直接跳出
            if ( current === target ) return;
            // 判断步长的正负
            var step = current>target ? -30 : 30;

            // 设置定时器移动
            el.timer = setInterval(function () {
                current = el.offsetLeft;
                // 如果最后的一步长度不够步长，就直接跳到target
                current += step;
                el.style.left = current + 'px';
                console.log(el.style.left);
                if ( Math.abs( current - target ) < Math.abs( step ) ) {
                    box.style.left = target + 'px';
                    clearInterval(el.timer);
                }
            }, 17)
            
        }
    </script>
</body>
</html>